package moe.oil.authority;


import lombok.extern.slf4j.Slf4j;
import moe.oil.authority.annotation.Permit;
import moe.oil.exception.user.UserPermissionsException;
import moe.oil.exception.user.UsernameNotFoundException;
import moe.oil.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
//todo 登录后存入Redis
public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //什么情况下handler不是一个HandlerMethod对象呢？当然是在没有找到匹配的方法的时候，
        if (!(handler instanceof HandlerMethod))
            //作用：拦截非注解方法
            return HandlerInterceptor.super.preHandle(request, response, handler);

        var method = ((HandlerMethod) handler).getMethod();

        var annotation = ((HandlerMethod) handler).getMethodAnnotation(Permit.class);
        if (annotation == null) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        var roleLevel = annotation.value();
        var id = jwtUtils.getUserIdByRequest(request);
        //opsForValue操作redis的值
        var opsForValue = redisTemplate.opsForValue();
        var role = (Integer) opsForValue.get(id.toString());

        if (role == null) {
            throw new UsernameNotFoundException("");

        } else if (role < roleLevel.getPermission()) {
            throw new UserPermissionsException();
        }
        return true;
    }
}
